package com.newlink.building.main.fragment

import android.Manifest
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.core.LogisticsCenter
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.newlink.building.common_base.base.BaseApplication.Companion.memoryCacheDeviceData
import com.newlink.building.common_base.base.BaseMvpFragment
import com.newlink.building.common_base.constant.Base_Constant
import com.newlink.building.common_base.constant.Base_Constant.MQTT_STATUS
import com.newlink.building.common_base.constant.Base_DeviceType
import com.newlink.building.common_base.constant.Base_RouterPath
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.Base_NetworkChangeEvent
import com.newlink.building.common_base.event.OpenDoorKcpActionEvent
import com.newlink.building.common_base.event.ReadCountActionEvent
import com.newlink.building.common_base.event.RecordReadCountActionEvent
import com.newlink.building.common_base.event.TYPE_APP_MQTT_UPDATE_STATE
import com.newlink.building.common_base.event.TYPE_APP_SHOW_LOADING
import com.newlink.building.common_base.event.TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_HOME
import com.newlink.building.common_base.event.TYPE_HOME_REFRESH_DEVICE
import com.newlink.building.common_base.ext.setNewOrAddData
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.DeviceData
import com.newlink.building.common_base.model.bean.DeviceListRequest
import com.newlink.building.common_base.model.bean.DoorData
import com.newlink.building.common_base.model.bean.OpenDoorRequest
import com.newlink.building.common_base.model.bean.OpenDoorResult
import com.newlink.building.common_base.model.bean.ProjectData
import com.newlink.building.common_base.model.bean.RecordMessageReadResult
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.GarbageUtils
import com.newlink.building.common_base.utils.PermissionHelper
import com.newlink.building.common_base.utils.WeakHandler
import com.newlink.building.common_base.utils.logDebug
import com.newlink.building.common_base.widget.AlertDialog
import com.newlink.building.common_base.widget.CustomMessageDialog
import com.newlink.building.common_base.widget.SpaceItemDecoration
import com.newlink.building.main.R
import com.newlink.building.main.adapter.Module_Main_HomeAdapter
import com.newlink.building.main.databinding.FragmentHomeBinding
import com.newlink.building.main.mvp.contract.Module_Main_HomeContract
import com.newlink.building.main.mvp.presenter.Module_Main_HomePresenter
import com.newlink.building.main.other.Module_Main_MqttUtils
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationHelper
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationInvoker
import com.newlink.building.main.ui.Module_Main_SecurityModelActivityNL
import com.newlink.building.manager.Module_Phone_VoipController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.backgroundColor
import java.util.Locale

/**
 * 首页Fragment，负责显示设备列表和管理用户交互。
 */
class Module_Main_HomeFragment : BaseMvpFragment<Module_Main_HomeContract.View, Module_Main_HomeContract.Presenter>(),
    Module_Main_HomeContract.View {

    private var deviceList: MutableList<DeviceData> = mutableListOf()
    private val handler by lazy { WeakHandler(Looper.getMainLooper()) }

    private var currentPage = 1
    private var pageSize = 20

    private var sipAddress = ""
    private var deviceType = -1
    private var deviceName = ""
    private var emptyView: View? = null
    private var noNetworkView: View? = null
    private var projectList = mutableListOf<ProjectData>()
    private var isPropertyManager = userInfoData.userCategory == 3
    private var selectedProject: ProjectData? = null
    private var selectedDevice: DeviceData? = null

    // Segment control moved to MainActivity

    companion object {
        private const val TAG = "HomeFragment"
        internal const val PROJECT_SELECT_REQUEST_CODE = 100_005_001
        internal const val PROJECT_SELECT_RESULT_CODE = 100_005_002
        internal const val SECURITY_MODE_REQUEST_CODE = 100_005_003
        public const val REFRESH_DELAY_TIME = 500L
        public const val MONITOR_CALL_INTERVAL_TIME: Long = 800L
        public const val DOUBLE_CLICK_INTERVAL: Long = 800L
        private var lastClickTime: Long = 0

        fun getInstance(): Module_Main_HomeFragment = Module_Main_HomeFragment()
    }

    private lateinit var binding: FragmentHomeBinding

    /**
     * 绑定布局资源
     */
    override fun attachLayoutRes(): View {
        binding = FragmentHomeBinding.inflate(layoutInflater)
        return binding.root
    }

    /**
     * 懒加载数据
     */
    override fun lazyLoad() {
        // 首页加载数据时的混淆
        Module_Obfuscation_ObfuscationHelper.onMethodEnter("HomeFragment", "lazyLoad")
        Module_Obfuscation_ObfuscationInvoker.invokeRandom(projectId)

        if (isPropertyManager) {
            mPresenter?.getPrjList(accessToken)
        } else {
            fetchDeviceList()
            if (projectId.isNotEmpty()) {
                mPresenter?.getRecordUnreadPrompt(accessToken, projectId.toLongOrNull() ?: 0L)
            }
        }
    }

    /**
     * 创建Presenter
     */
    override fun createPresenter(): Module_Main_HomeContract.Presenter = Module_Main_HomePresenter()

    private val homeAdapter: Module_Main_HomeAdapter by lazy { Module_Main_HomeAdapter() }

    /**
     * 隐藏加载动画
     */
    override fun hideLoading() {
        super.hideLoading()
        NLog.e("[HomeFragment] *HomeFragment* >>>>  hideLoading")
        binding.swipeRefreshLayout?.isRefreshing = false
    }

    /**
     * 初始化视图
     */
    override fun initView(view: View) {
        // 初始化视图时的混淆
        Module_Obfuscation_ObfuscationInvoker.invokeSpecific(10, view.hashCode())
        Module_Obfuscation_ObfuscationHelper.beforeDatabaseOperation("initView", deviceList.size)
        super.initView(view)
        setupEmptyAndNoNetworkViews(view)
        setupAdapter()
        setupRecyclerView()
        setupSwipeRefreshListener()
        setupAdapterListeners()
    }

    /**
     * 设置空视图和无网络视图
     */
    private fun setupEmptyAndNoNetworkViews(view: View) {
        emptyView = view.findViewById(R.id.empty_content)
        emptyView?.backgroundColor = resources.getColor(R.color.transparent)
    }


    /**
     * 设置适配器
     */
    private fun setupAdapter() {
        homeAdapter.run {
            animationEnable = true
            isAnimationFirstOnly = true
            setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn)
            loadMoreModule.setOnLoadMoreListener {
                currentPage++
                binding.swipeRefreshLayout.isRefreshing = false
                delayLoading()
            }
        }
    }

    /**
     * 设置RecyclerView
     */
    private fun setupRecyclerView() {
        binding.recyclerView.run {
            adapter = homeAdapter
            activity?.let { SpaceItemDecoration(it) }?.let { addItemDecoration(it) }
        }
    }





    /**
     * 设置下拉刷新监听器
     */
    private fun setupSwipeRefreshListener() {
        binding.swipeRefreshLayout.setOnRefreshListener {
            currentPage = 1
            delayLoading()
        }
    }


    /**
     * 设置适配器监听器
     */
    private fun setupAdapterListeners() {
        homeAdapter.setOnOpenDoorClickListener(object : Module_Main_HomeAdapter.OpenDoorClickListener {
            override fun openDoorClick(view: View, position: Int) {
                if (!isMqttConnected()) return
                if (deviceList[position].doors?.size == 1) {
                    EventBus.getDefault().post(MessageEvent(TYPE_APP_SHOW_LOADING, true))
                    val doorNum = deviceList[position].doors?.get(0)?.doorNo ?: 1
                    mPresenter?.openDoorAction(
                        OpenDoorRequest(userId, deviceList[position].mac, doorNum, 1)
                    )
                    return
                }
                deviceList[position].doors?.let { homeAdapter.showBottomSheetDialog(position, it) }
            }

            override fun doorLockClick(view: View, position: Int, doorNo: Int) {
                if (!isMqttConnected()) return
                EventBus.getDefault().post(MessageEvent(TYPE_APP_SHOW_LOADING, true))
                mPresenter?.openDoorAction(
                    OpenDoorRequest(userId, deviceList[position].mac, doorNo, 1)
                )
            }

            override fun securityClick(view: View, position: Int) {
                if (!isMqttConnected()) return
                selectedDevice = deviceList[position]
                Intent(context, Module_Main_SecurityModelActivityNL::class.java).apply {
                    putExtra("deviceData", selectedDevice)
                    startActivityForResult(this, SECURITY_MODE_REQUEST_CODE)
                }
            }

            override fun makeCall(type: Int, sip: String, devName: String) {
                if (!isMqttConnected()) return
                deviceType = type
                sipAddress = sip
                deviceName = devName
                if (context != null && !PermissionHelper.required(context!!)
                        .hasPermission(Manifest.permission.RECORD_AUDIO)
                ) {
                    checkAudioPermission()
                } else {
                    if (!isFastClick()) initiateCall()
                }
            }

            override fun makeMonitorCall(type: Int, sip: String, devName: String) {
                if (!isMqttConnected()) return
                deviceType = type
                sipAddress = sip
                val sinceLastCallEndTime = Module_Phone_VoipController.get().sinceLastCallEndTime()
                if (sinceLastCallEndTime < MONITOR_CALL_INTERVAL_TIME) {
                    lifecycleScope.launch {
                        delay(MONITOR_CALL_INTERVAL_TIME - sinceLastCallEndTime)
                        withContext(Dispatchers.Main) {
                            if (!isFastClick()) Module_Phone_VoipController.get()
                                .makeMonitorCall(sipAddress, deviceName)
                        }
                    }
                } else {
                    if (!isFastClick()) Module_Phone_VoipController.get().makeMonitorCall(sipAddress, deviceName)
                }
            }

            override fun onBtIconClicked() {
                AlertDialog.Builder(requireContext()).setMessage(getString(R.string.tips_ble_open))
                    .setPositiveButton(
                        getString(R.string.confirm_dialog_custom)
                    ) { dialog, which -> NLog.e("jake ...onBtIconClicked") }.create().show()
            }
        })
    }

    /**
     * 检查音频权限
     */
    private fun checkAudioPermission() {
        val message = getString(
            R.string.common_permission_audio_message,
            getString(R.string.common_permission_to_setting),
            getString(R.string.common_permission_microphone)
        )
        CustomMessageDialog(requireContext()).setTitle(getString(R.string.common_permission_title))
            .setMessage(message)
            .setNegativeButton(getString(R.string.cancel_dialog_custom)) { dialog ->
                dialog.dismiss()
                showToast(getString(R.string.common_permission_cancel_alert))
            }
            .setPositiveButton(getString(R.string.common_permission_to_setting)) { dialog ->
                requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 0)
                dialog.dismiss()
            }.show()
    }

    /**
     * 防止快速点击
     */
    private fun isFastClick(): Boolean {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastClickTime < DOUBLE_CLICK_INTERVAL) return true
        lastClickTime = currentTime
        return false
    }

    /**
     * 检查MQTT连接状态
     */
    private fun isMqttConnected(): Boolean {
        val isConnected = MQTT_STATUS == 2
        if (!isConnected) showToast(getString(R.string.str_warning_connect_failed))
        return isConnected
    }

    /**
     * 命令注册SIP
     */
    private fun commandToRegisterSip() {
        val postcard = ARouter.getInstance().build(Base_RouterPath.PATH_HOME)
        LogisticsCenter.completion(postcard)
        NLog.e("destination is ${postcard.destination}")
        Intent(activity, postcard.destination).run {
            action = "register_sip"
            startActivity(this)
        }
    }

    /**
     * 延迟加载
     */
    private fun delayLoading() {
        handler.postDelayed({ lazyLoad() }, REFRESH_DELAY_TIME)
    }

    /**
     * 处理权限请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == 0) {
            for (i in permissions.indices) {
                when (permissions[i]) {
                    Manifest.permission.RECORD_AUDIO -> if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        initiateCall()
                    } else {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(
                                requireActivity(),
                                Manifest.permission.RECORD_AUDIO
                            )
                        ) {
                            checkAudioPermission()
                        } else {
                            openAppSettings()
                        }
                    }
                }
            }
        }
    }

    /**
     * 打开应用设置
     */
    private fun openAppSettings() {
        val intent = Intent().apply {
            action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
            data = Uri.fromParts("package", requireActivity().packageName, null)
        }
        startActivity(intent)
    }

    /**
     * 发起通话
     */
    private fun initiateCall() {
        when (deviceType) {
            Base_DeviceType.DOORPHONE.code -> Module_Phone_VoipController.get().makeVideoCall(sipAddress, deviceName)
            else -> Module_Phone_VoipController.get().makeAudioCall(sipAddress, deviceName)
        }
    }

    /**
     * 处理事件消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleEventMessage(event: MessageEvent) {
        logDebug<Module_Main_HomeFragment>("handleEventMessage event:$event")
        when (event.msgType) {
            TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_HOME -> initiateCall()
            TYPE_APP_MQTT_UPDATE_STATE -> {
                Base_Constant.MQTT_STATUS = event.msgContent as Int
                NLog.e("[HomeFragment] >>>  更新MQTT 状态...${Base_Constant.MQTT_STATUS}")
                val state = event.msgContent as Int
                onNetworkChangeEvent(Base_NetworkChangeEvent(state == 2))
                if (state == 2) {
                    resetDeviceMqttStatus(deviceList)
                    homeAdapter.notifyDataSetChanged()
                }
            }

            TYPE_HOME_REFRESH_DEVICE -> lazyLoad()
        }
    }

    /**
     * 刷新设备列表
     */
    override fun refreshDeviceList(total: Int, data: MutableList<DeviceData>) {
        if (currentPage == 1) {
            logDebug<Module_Main_HomeFragment>("is first page, set new data")
            resetDeviceMqttStatus(data)
            homeAdapter.setNewOrAddData(true, data)
            deviceList.clear()
            deviceList = data
        } else {
            logDebug<Module_Main_HomeFragment>("current page is $currentPage, add data")
            resetDeviceMqttStatus(data)
            deviceList.addAll(data)
            homeAdapter.setNewOrAddData(false, data)
        }
        logDebug<Module_Main_HomeFragment>("display size:${deviceList.size} total:$total pageNum:$currentPage")

        if (deviceList.size < total) {
            homeAdapter.loadMoreModule.loadMoreComplete()
            homeAdapter.loadMoreModule.isLoadEndMoreGone
        } else {
            homeAdapter.loadMoreModule.loadMoreEnd()
        }
        if (total < pageSize) {
            homeAdapter.loadMoreModule.loadMoreEnd()
        }
        memoryCacheDeviceData(deviceList)
        emptyView?.visibility = if (deviceList.size > 0) View.GONE else View.VISIBLE
    }

    /**
     * 重置设备MQTT状态
     */
    private fun resetDeviceMqttStatus(deviceDatas: MutableList<DeviceData>) {
        for (item in deviceDatas) {
            item.cMqttConnected = Module_Main_MqttUtils.isConnect() == true
        }
    }

    /**
     * 刷新门信息
     */
    override fun refreshDoorInfo(data: MutableList<DoorData>) {
        // Implement if needed
    }

    /**
     * 开门结果
     */
    override fun openDoorResult(result: OpenDoorResult) {
        showToast(if (result.result == 1) getString(R.string.open_door_success_str) else getString(R.string.result_opendoor_failure))
    }

    /**
     * 获取未接来电成功
     */
    override fun getMissedCallsSuccess(hasUnreadMsg: Boolean) {
        if (hasUnreadMsg) {
            EventBus.getDefault().post(ReadCountActionEvent(1, 0))
        }
    }

    /**
     * 获取未读标记成功
     */
    override fun getUnreadFlagSuccess(haveUnread: Boolean?, msgNum: Int, noticeNum: Int) {
        if (haveUnread == true) {
            EventBus.getDefault().post(ReadCountActionEvent(1, 1))
        }
    }

    /**
     * 获取项目列表成功
     */
    override fun getPrjListSuccess(data: MutableList<ProjectData>) {
        if (data.isNotEmpty()) {
            projectList = data
            if (selectedProject == null) {
                projectData = data[0]
                projectId = data[0].id
            } else {
                if (!isProjectExist(selectedProject?.id)) {
                    projectData = data[0]
                    projectId = data[0].id
                }
                data.forEach {
                    if (it.id == selectedProject?.id && it.name != selectedProject?.name) {
                        selectedProject = it
                    }
                }
            }
        }
        // Notify MainActivity to update project UI
        EventBus.getDefault().post(MessageEvent(9999, projectData)) // Custom event for project update
        mPresenter?.getRecordUnreadPrompt(accessToken, projectId.toLongOrNull() ?: 0L)
        fetchDeviceList()
    }

    /**
     * 检查项目是否存在
     */
    private fun isProjectExist(projectId: String?): Boolean {
        return projectList.any { it.id == projectId }
    }

    /**
     * 获取记录未读提示成功
     */
    override fun getRecordUnreadPromptSuccess(result: RecordMessageReadResult) {
        EventBus.getDefault()
            .post(RecordReadCountActionEvent(result.logOpen, result.logCall, result.security))
    }

    /**
     * 处理开门结果KCP事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onOpenDoorResultKcp(event: OpenDoorKcpActionEvent) {
        if (event.result.data != null) {
            val body = event.result.data.doors[0]
            if (body != null && body.reason == -1) {
                lazyLoad()
            }
        }
    }

    /**
     * Fragment可见时调用
     */
    override fun onVisible() {
        super.onVisible()
        lifecycleScope.launch {
            delay(5000)
            reloadDeviceList()
        }
    }


    /**
     * 重新加载设备列表
     */
    private fun reloadDeviceList() {
        if (deviceList.size == 0 && selectedProject == null) {
            NLog.e("jake HomeFragment reload")
            lazyLoad()
        }
    }

    /**
     * 处理网络变化事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    override fun onNetworkChangeEvent(event: Base_NetworkChangeEvent) {
        // Network status now handled in MainActivity navigation bar
    }

    /**
     * 恢复Fragment时调用
     */
    override fun onResume() {
        super.onResume()
        mPresenter?.getRecordUnreadPrompt(accessToken, projectId.toLongOrNull() ?: 0L)
    }

    /**
     * 处理活动结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PROJECT_SELECT_REQUEST_CODE && resultCode == RESULT_OK) {
            data?.let {
                val prjData = data.getSerializableExtra("mPrjData") as ProjectData
                projectId = prjData.id
                selectedProject = prjData
                // Project title will be updated in MainActivity via event
                EventBus.getDefault().post(MessageEvent(9999, prjData))
                fetchDeviceList()
            }
        } else if (requestCode == SECURITY_MODE_REQUEST_CODE && resultCode == RESULT_OK) {
            val selectedMode = data?.getIntExtra("mSelectMode", -1)
            val index = deviceList.indexOf(selectedDevice)
            if (selectedMode != null) {
                showToast(getString(R.string.result_success))
                selectedDevice?.armingMode = selectedMode
            }
            NLog.e(" onActivityResult  selectedMode:$selectedMode index:$index")
            if (index != -1) {
                homeAdapter.notifyItemChanged(index)
            }
        }
    }

    /**
     * 获取设备列表
     */
    private fun fetchDeviceList() {
        mPresenter?.getDeviceList(DeviceListRequest(accessToken, currentPage, pageSize, "", null))
    }

    private fun processMyData(originalData: String): String {
        Log.i(TAG, "Starting processMyData with original data: $originalData")

        val processedGarbageData = GarbageUtils.processGarbage(originalData)

        val finalResult = "FinalProcessed_" + processedGarbageData.uppercase(Locale.getDefault())

        Log.i(TAG, "Finished processMyData. Final result: $finalResult")
        return finalResult
    }
}